package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.common.exception.CustomException;
import com.heima.gateway.utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 王可
 * @Date: 2021/01/29/8:28
 * @Description:
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.web-server-url}")
    private String fileServerUrl;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    @Resource
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        // 1. 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //    检查登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 封装条件
        // 2.1  分页条件
        Page<WmNews> pageRequest = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery();
        // 2.2  检查状态条件
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 2.3  检查关键字条件  模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 2.4  检查频道条件
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 2.5  检查发布日期 时间条件
        if (dto.getBeginPubDate() != null) {
            lambdaQueryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }

        if (dto.getEndPubDate() != null) {
            lambdaQueryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }


        // 2.6  检查登录用户ID条件
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        // 2.7  按照文章的发布时间来排序
        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);

        // 3. 执行查询  封装结果
        IPage<WmNews> pageResult = page(pageRequest, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        responseResult.setHost(fileServerUrl);
        responseResult.setData(pageResult.getRecords());
        return responseResult;
    }

    @Transactional
    @Override
    public ResponseResult saveNews(WmNewsDto dto) {
        //检查参数
        if (dto == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //状态只能是草稿或者提交，不能是其他属性
        System.out.println(checkStatus(dto.getStatus()));
        if (!checkStatus(dto.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检查用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //将dto的内容拷贝到wmNews中，因为image是list，无法直接赋值，需要手动赋值
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }

        //image属性需要手动的赋值
        //因为wmNews中的image是string类型，dto中的属性是json类型，需要转型
        //多实行需要遍历。流
        List<String> images = dto.getImages();
        if (images != null && !images.isEmpty()) {
            images = images.stream()
                    //将图片地址重新设置为符合的格式，去除ngaix代理的地址
                    .map(map -> map.replace(fileServerUrl, "").trim())
                    .collect(Collectors.toList());
            //拼接数据
            String join = StringUtils.join(images, ",");
            //设置数据
            wmNews.setImages(join);
        }

        //保存或需改文章
        wmNews.setUserId(user.getId());
        saveOrUpdateArticle(wmNews);

        //设置内容和图片引用关系
        //抽取内容中所用的相关图片的集合
        List<String> contentPictureUri = getContentPictureUri(dto.getContent());

        //保存自媒体文章和相关图片的关联关系
        if (contentPictureUri != null && !contentPictureUri.isEmpty() && !WmNews.Status.NORMAL.getCode().equals(dto.getStatus())) {
            saveRelativesBetweenArticleAndPicture(contentPictureUri,
                    wmNews.getId(), WemediaContans.WM_CONTENT_REFERENCE);
        }

        // 保存封面图片对应的素材和自媒体文章的关联关系
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType()) && contentPictureUri != null
                && !contentPictureUri.isEmpty()) {
            images = autoSetCoverImages(wmNews, contentPictureUri);
        }

        if (images != null && !images.isEmpty() && !WmNews.Status.NORMAL.getCode().equals(dto.getStatus())) {
            saveRelativesBetweenArticleAndPicture(images, wmNews.getId(), WemediaContans.WM_COVER_REFERENCE);
        }

        //远程自动调用
        if(wmNews.getStatus()==1){
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = getById(id);

        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该文章不存在");
        }

        //判断文章的状态，发布的文章不能删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请先下架该文章");
        }

        //删除关联表
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                            .eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //删除文章
        removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    //判断提交的状态，状态为0（正常）或状态为1（提交）为true
    public boolean checkStatus(Short status) {
        if (status != null && (status.equals(WmNews.Status.NORMAL.getCode())
                || status.equals(WmNews.Status.SUBMIT.getCode()))) {
            return true;
        }
        return false;
    }

    //保存或修改自媒体文章
    public void saveOrUpdateArticle(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    public List<String> getContentPictureUri(String content) {
        ArrayList<String> uriList = new ArrayList<>();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        for (Map map : maps) {
            if (WemediaContans.WM_NEWS_TYPE_IMAGE.equals(map.get("type"))) {
                String imageUrl = (String) map.get("value");
                uriList.add(imageUrl.replace(fileServerUrl, "").trim());
            }
        }
        return uriList;
    }

    public void saveRelativesBetweenArticleAndPicture(List<String> imageList, Integer newsId, Short type) {

        //根据当前用户id和图片列表查询出对应的素材信息(用于上传图片时在收藏库里找图片上传)
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .in(WmMaterial::getUrl, imageList)
        );
        if (wmMaterials == null && wmMaterials.isEmpty()) {
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST
                    , "关联素材不存在"));
        }

        //判断当前图片在素材库里存不存在，不存在抛异常
        ArrayList<Integer> materialIds = new ArrayList<>();
        Map<String, Integer> urlAndIds = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (int i = 0; i < imageList.size(); i++) {
            String url = imageList.get(i);
            if (!urlAndIds.containsKey(url)) {
                throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                        "关联素材不存在"));
            }
            materialIds.add(urlAndIds.get(url));
        }

        //将信息保存到数据库中
        for (int i = 0; i < materialIds.size(); i++) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(materialIds.get(i));
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd((short) i);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
    }

    public List<String> autoSetCoverImages(WmNews wmNews, List<String> imageList) {
        int size = imageList.size();
        List<String> imagesCover = new ArrayList<>();
        if (size > 2) {//多图模式
            wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
            imagesCover = imageList.stream().limit(3).collect(Collectors.toList());
        } else if (size > 0 && size <= 2) {
            wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
            imagesCover = imageList.stream().limit(1).collect(Collectors.toList());
        } else {
            wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
        }

        //更新文章信息
        wmNews.setImages(StringUtils.join(imagesCover, ","));
        updateById(wmNews);
        return imagesCover;
    }
}
